//
//  MZExtensionUIButton.swift
//  MZTool
//
//  Created by gby on 2022/3/7.
//

import UIKit

extension UIButton{
    
    static var expandegdKey = "expandegdKey"
    private var expandEgdinsetsStr: String? {
        get { return objc_getAssociatedObject(self, &UIButton.expandegdKey) as? String }
        set { objc_setAssociatedObject(self, &UIButton.expandegdKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
    }
    
    public func expandEdgInsets(_ edg:UIEdgeInsets) {
        self.expandEgdinsetsStr = NSCoder.string(for: edg)
    }
    
    open override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        var rect: CGRect = self.bounds
        if let str = self.expandEgdinsetsStr {
            let edg = NSCoder.uiEdgeInsets(for: str)
            rect = CGRect.init(
                x: self.bounds.origin.x - edg.left,
                y: self.bounds.origin.y - edg.top,
                width: self.bounds.size.width + edg.left + edg.right,
                height: self.bounds.size.height + edg.top + edg.bottom
            )
            return rect.contains(point)
        }
        return super.point(inside: point, with: event)
    }
    
}

extension MZKit where Base == UIButton {
     
    public func putIMGRight(_ space: CGFloat = 0) {
        base.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: -(base.imageView?.mz.width ?? 0), bottom: 0, right: base.imageView?.mz.width ?? 0)
        base.imageEdgeInsets = UIEdgeInsets.init(top: 0, left: base.titleLabel?.mz.width ?? 0, bottom: 0, right: -(base.titleLabel?.mz.width ?? 0) - space)
    }

    public func putIMGTop(space: CGFloat) {
        guard let labv = base.titleLabel, let imgv = base.imageView else {
            return
        }

        let upTop = (labv.mz.height + space)/2
        let downTop = imgv.mz.height/2 + space/2

        base.titleEdgeInsets = UIEdgeInsets.init(
            top: downTop,
            left: -(imgv.mz.width/2),
            bottom: -downTop,
            right: (imgv.mz.width/2)
        )
        base.imageEdgeInsets = UIEdgeInsets.init(
            top: -upTop,
            left: (labv.mz.width/2),
            bottom: upTop,
            right: -(labv.mz.width/2)
        )
    }

    public func putIMGBottom(space: CGFloat) {
        guard let labv = base.titleLabel, let imgv = base.imageView else {
            return
        }
        let upTop = (imgv.mz.height + space)/2
        let downTop = labv.mz.height/2 + space/2
        base.titleEdgeInsets = UIEdgeInsets.init(
            top: -upTop,
            left: -(imgv.mz.width/2),
            bottom: upTop,
            right: (imgv.mz.width/2)
        )
        base.imageEdgeInsets = UIEdgeInsets.init(
            top: downTop,
            left: (labv.mz.width/2),
            bottom: -downTop,
            right: -(labv.mz.width/2)
        )
    }
    
}
